import React, { Component } from "react";
import { connect } from "react-redux";
import { Button, Modal, message, Popover } from "antd";
import { AdvancedTable } from "components/index";
import Selector from "components/selector";
import { messages } from "share/common";
import moment from "moment";
import EditDate from "../../../pay/template/edit-date";
import httpFetch from "share/httpFetch";
import constant from "./constant";
import menuRoute from "routes/menuRoute";
import Space from "components/space";

class AccrualManagementConfirm extends Component {
  onSelectChange = (selectedRowKeys) => {
    let { rowSelection } = this.state;
    rowSelection.selectedRowKeys = selectedRowKeys;
    this.setState({ rowSelection });
  };

  onSelectItem = (record, selected) => {
    const { selectedData } = this.state;
    if (selected) {
      selectedData.push(record);
    } else {
      selectedData.deleteObj(record, "index");
    }
    this.setState({ selectedData });
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    changeRows.map((changeRow) => this.onSelectItem(changeRow, selected));
  };

  componentDidMount = () => {
    this.setState({ loading: true });
    httpFetch
      .get(`/api/periods/recent/query?setOfBooksId=${this.props.company.setOfBooksId}`)
      .then((res) => {
        if (res.data && res.data.length) {
          this.advancedTableRef.advancedSearchRef.props.form.setFieldsValue({
            periodSetCode: [{ periodName: res.data[0].periodName }],
          });
          this.setState({ loading: false }, this.advancedTableRef.advancedSearchRef.search);
        } else {
          this.setState({ loading: false });
          message.error(messages("finance-10.key76") /*无默认会计期间*/);
        }
      })
      .catch((e) => {
        this.setState({ loading: false });
        message.error(e.response.data.message);
      });
  };

  state = {
    searchForm: [
      {
        component: (isTitle) => (
          <Selector
            allowClear={false}
            type={"setOfBooksByTenant"}
            params={{ roleType: "TENANT" }}
            entity
            onChange={(value) => this.handleChangeSetOfBook(value, isTitle)}
          />
        ),
        id: "setOfBooksId",
        judgeInTitle: true,
        label: messages("finance-4.key66") /*账套*/,
        initialValue: {
          setOfBooksName: this.props.company.setOfBooksName,
          id: this.props.company.setOfBooksId,
        },
        tagUnclosed: true,
        parser: (value) => ({ setOfBooksId: value ? value.id : undefined }),
        tagParser: (value) => value.setOfBooksName,
      },
      {
        id: "companyId",
        label: messages("finance-10.key23") /*公司*/,
        component: "Chooser",
        props: {
          type: "available_company_setOfBooks",
          labelKey: "name",
          valueKey: "id",
          single: true,
          listExtraParams: {
            enabled: true,
            setOfBooksId: this.props.company.setOfBooksId,
          },
        },
        initialValue: [{ name: this.props.company.name, id: this.props.company.id }],
        parser: (value) => ({
          companyId: value && value.length ? value[0].id : null,
        }),
      },
      {
        id: "periodSetCode",
        label: messages("finance-10.key24") /*预提会计期间*/,
        component: "Chooser",
        props: {
          labelKey: "periodName",
          valueKey: "periodName",
          type: "period_set",
          single: true,
          showClear: false,
          listExtraParams: { setOfBooksId: this.props.company.setOfBooksId },
        },
        tagUnclosed: true,
        parser: (value) => ({
          periodSetCode: value && value.length ? value[0].periodName : undefined,
        }),
        tagParser: (value) => value.map((item) => item.periodName).join(","),
      },
      {
        id: "createdDate",
        label: messages("finance-10.key77") /*单据提交日期*/,
        component: "DateRangePicker",
        parser: (value) => ({
          createdDateFrom: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : undefined,
          createdDateTo: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : undefined,
        }),
        initialValue: [moment().subtract(1, "month"), moment()],
      },
      {
        id: "bookDate",
        label: messages("finance-10.key25") /*费用发生日期*/,
        component: "DateRangePicker",
        parser: (value) => ({
          bookDateFrom: value && value[0] ? moment(value[0]).format("YYYY-MM-DD 00:00:00") : undefined,
          bookDateTo: value && value[1] ? moment(value[1]).format("YYYY-MM-DD 23:59:59") : undefined,
        }),
        initialValue: [moment().subtract(1, "month"), moment()],
      },
    ],
    loading: false,
    rowSelection: {
      selectedRowKeys: [],
      onChange: this.onSelectChange,
      onSelect: this.onSelectItem,
      onSelectAll: this.onSelectAll,
    },
    selectedData: [],
  };

  handleChangeSetOfBook = (value, isTitle) => {
    const { searchForm } = this.state;
    let setOfBooksId = searchForm.find((item) => item.id === "companyId").props.listExtraParams.setOfBooksId;
    if (setOfBooksId !== value.id) {
      if (!isTitle) {
        this.advancedTableRef.advancedSearchRef.props.form.setFieldsValue({
          companyId: undefined,
          periodSetList: undefined,
        });
      }
      searchForm.map((item) => {
        if (item.id === "companyId" || item.id === "periodSetList") {
          item.props.listExtraParams = {
            setOfBooksId: value.id,
            enabled: true,
          };
        }
      });
      this.wrappedInstance.setState({ searchForm });
    }
  };

  service = (page, size, searchParams) => {
    return httpFetch.post(`/api/accrued/expense/batch/pre/query`, {
      ...searchParams,
    });
  };

  columns = [
    { title: messages("finance-10.key26") /*批次号*/, dataIndex: "batchNumber" },
    { title: messages("finance-10.key27") /*批次账套*/, dataIndex: "setOfBooksName" },
    { title: messages("finance-10.key28") /*批次公司*/, dataIndex: "companyName" },
    {
      title: messages("finance-10.key29") /*预提记账日期*/,
      dataIndex: "bookDate",
      render: (value, record) =>
        record.status && [1001, 1002, 1003].indexOf(record.status) > -1 ? (
          <EditDate
            value={moment(value)}
            onChange={(value) => this.handleEditRecord(value, record, "bookDate")}
            startDate={record.bookDateFrom}
            endDate={record.bookDateTo}
          />
        ) : (
          moment(value).format("YYYY-MM-DD")
        ),
    },
    {
      title: messages("finance-10.key30") /*预提冲销记账日期*/,
      dataIndex: "reverseBookDate",
      render: (value, record) =>
        record.status && [1001, 1002, 1003].indexOf(record.status) > -1 ? (
          <EditDate
            value={moment(value)}
            onChange={(value) => this.handleEditRecord(value, record, "reverseBookDate")}
            startDate={record.reverseBookDateFrom}
            endDate={record.reverseBookDateTo}
          />
        ) : (
          moment(value).format("YYYY-MM-DD")
        ),
    },
    {
      title: messages("common.column.status") /*状态*/,
      dataIndex: "status",
      render: (value) => constant.statusMap[value],
    },
    {
      title: messages("common.operation") /*操作*/,
      dataIndex: "operator",
      render: (value, record) =>
        record.status ? (
          <span>
            <a onClick={() => this.onViewDetail(record)}>{messages("finance-10.key31") /*查看明细*/}</a>
            <span className="ant-divider" />
            <a onClick={() => this.onViewTotal(record)}>{messages("finance-10.key32") /*查看汇总*/}</a>
          </span>
        ) : (
          "-"
        ),
    },
  ];

  handleEditRecord = (value, record, type) => {
    this.setState({ loading: true });
    httpFetch
      .post(`/api/accrued/expense/batch/edit`, {
        ...record,
        [type]: value,
      })
      .then(() => {
        this.setState({ loading: false }, this.advancedTableRef.getList);
      })
      .catch((e) => {
        this.setState({ loading: false });
        message.error(e.response.data.message);
      });
  };

  onViewDetail = (record) => {
    this.context.router.push(
      menuRoute.getRouteItem("detail-view").url.replace(":accruedExpenseBatchId", record.accruedExpenseBatchId)
    );
  };

  onViewTotal = (record) => {
    this.context.router.push(
      menuRoute.getRouteItem("total-view").url.replace(":accruedExpenseBatchId", record.accruedExpenseBatchId)
    );
  };

  handleConfirm = () => {
    const { loading } = this.state;
    Modal.confirm({
      title: messages("finance-10.key33") /*确认预提*/,
      content: "是否确认预提？确认后，该预提批次会直接生成预提凭证或者先去复核",
      onOk: () => this.handleOk("confirm"),
    });
  };

  handleCreate = () => {
    Modal.confirm({
      title: messages("finance-10.key34") /*确认生成预提批次*/,
      content: messages(
        "finance-10.key73"
      ) /*是否确定生成预提批次？确定后，系统会拉取最新业务数据生成批次号，请耐心等待*/,
      onOk: () => this.handleOk("create"),
    });
  };

  handleCancel = () => {
    Modal.confirm({
      title: messages("finance-10.key78") /*确定取消预提*/,
      content: messages("finance-10.key74") /*是否确定取消预提？取消后，该预提批次会归档，需要重新触发生成预提批次*/,
      onOk: () => this.handleOk("cancel"),
    });
  };

  handleOk = (type) => {
    const { selectedData, rowSelection } = this.state;
    let temp = {
      create: `/api/accrued/expense/batch/create`,
      cancel: `/api/accrued/expense/batch/withdraw`,
      confirm: `/api/accrued/expense/batch/submit`,
    };
    this.setState({ loading: true });
    let params = {};
    type === "create"
      ? (params.accruedExpenseBatchDTOS = selectedData.filter((item) => !item.status))
      : (params.accruedExpenseBatchIds = selectedData
          .map((item) => item.accruedExpenseBatchId)
          .filter((item) => !!item));
    httpFetch
      .post(temp[type], params)
      .then(() => {
        rowSelection.selectedRowKeys = [];
        this.setState({ loading: false, selectedData: [], rowSelection }, this.advancedTableRef.getList);
      })
      .catch((e) => {
        this.setState({ loading: false });
        message.error(e.response.data.message);
      });
  };

  handleSearch = () => {
    const { periodSetCode } = this.advancedTableRef.advancedSearchRef.props.form.getFieldsValue();
    if (periodSetCode && periodSetCode.length) {
      this.advancedTableRef.getList();
    }
  };

  render() {
    const { searchForm, loading, rowSelection } = this.state;
    return (
      <AdvancedTable
        service={this.service}
        tableName={"accrual-management-confirm"}
        index
        title={messages("finance-10.key37") /*预提批次确认*/}
        onRef={(ref) => (this.advancedTableRef = ref)}
        searchForm={searchForm}
        pageCacheEnable={false}
        searchNotGetList
        onSearch={this.handleSearch}
        columns={this.columns}
        rowKey="index"
        rowSelection={rowSelection}
        propsLoading={loading}
        onGetDataError={(e) => {
          message.error(e.response.data.message);
        }}
        pagination={null}
        footer={
          <Space>
            <Popover content={messages("finance-10.key38") /*所选数据中，状态为空的会自动生成批次*/}>
              <Button onClick={this.handleCreate}>{messages("finance-10.key39") /*生成预提批次*/}</Button>
            </Popover>
            <Popover content={messages("finance-10.key40") /*所选数据中，状态为“待预提”的会归档并且状态回退到“空”*/}>
              <Button onClick={this.handleCancel}>{messages("finance-10.key41") /*取消预提*/}</Button>
            </Popover>
            <Popover content={messages("finance-10.key42") /*所选数据中，状态为“待预提”的会提交去预提记账或者复核*/}>
              <Button onClick={this.handleConfirm}>{messages("finance-10.key33") /*确认预提*/}</Button>
            </Popover>
          </Space>
        }
      />
    );
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.loginCompany,
  };
}

AccrualManagementConfirm.contextTypes = {
  router: React.PropTypes.object,
};

export default connect(mapStateToProps)(AccrualManagementConfirm);
